package com.hk.service.order.impl;

import java.math.BigDecimal;
import java.util.List;

import com.hk.commons.*;
import com.hk.service.IUserChannel;
import org.json.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import com.hk.commons.enm.ConfirmStatusEnum;
import com.hk.commons.enm.PayStatusEnum;
import com.hk.commons.entity.Organization;
import com.hk.commons.entity.order.OrderInfo;
import com.hk.commons.entity.order.OrderRouteInfo;
import com.hk.commons.entity.product.Company;
import com.hk.commons.entity.product.Payment;
import com.hk.commons.entity.product.ProductInfo;
import com.hk.commons.entity.sys.SysUser;
import com.hk.commons.utils.order.OrderCreateMsg;
import com.hk.commons.vo.OrderStrMsg;
import com.hk.dao.base.impl.BaseServiceImpl;
import com.hk.service.IFundInfo_Yimi;
import com.hk.service.IOrganization;
import com.hk.service.kyc.IUserCard;
import com.hk.service.order.IOrderHandle;
import com.hk.service.order.IOrderInfo;
import com.hk.service.order.IOrderRouteInfo;
import com.hk.service.order.IOrderStatements;
import com.hk.service.order.IPayment;
import com.hk.service.order.IReservation;
import com.hk.service.product.ICompany;
import com.hk.service.product.IProductInfo;
import com.hk.service.sys.IBank;
import com.hk.service.sys.ISysUser;
import com.hk.service.sys.ISysUserRoles;

@Service
public class HkOrderHandleImpl extends BaseServiceImpl<OrderInfo> implements
		IOrderHandle<OrderInfo> {

	private Logger logger = LoggerFactory.getLogger(HkOrderHandleImpl.class);
	@Value("${qingniu.pdf}")
	private String QN_PDF;

	@Autowired
	private IReservation reservationService;

	@Autowired
	private IOrderRouteInfo orderRouteService;

	@Autowired
	private IUserChannel userChannelService;

	@Autowired
	private ISysUser userService;

	@Autowired
	private IBank bankService;

	@Autowired
	private IPayment paymentService;

	@Autowired
	private IOrderStatements orderStatementsService;

	@Autowired
	private IProductInfo productService;

	@Autowired
	private ICompany comService;

	@Autowired
	private IFundInfo_Yimi fundInfoService;

	@Autowired
	private IOrderInfo orderService;

	@Autowired
	private IOrganization orgService;

	@Autowired
	private ISysUserRoles roleService;

	@Autowired
	private IUserCard userCardService;

	@Override
	public Long createOrderRoute(Long userId, Long orderId, Integer companyId) {
		OrderInfo orderInfo = orderService.findById(orderId);

		OrderRouteInfo orderRouteInfo = new OrderRouteInfo();
		orderRouteInfo.setUserId(userId);
		orderRouteInfo.setCompanyId(companyId);
		orderRouteInfo.setOrderId(orderId);
		orderRouteInfo.setBrokerOrderNo("hk" + orderId);
		// orderRouteInfo.setProductId(orderInfo.getId());
		orderRouteInfo.setProductId(orderInfo.getProductId());

		SysUser user = userService.findById(userId);
		if (user != null && StringHelper.isNotEmpty(user.getRecommendCode())) {
			SysUser finUser = userService
					.getByPhoneNum(user.getRecommendCode());
			if (finUser != null) {
				orderRouteInfo.setFinancialPlannerId(finUser.getId());
			}

			if (StringHelper.isNotEmpty(user.getAccountId())) {
				orderRouteInfo.setAccountId(user.getAccountId());
			}
		}

		Long routeInfoId = orderRouteService.add(orderRouteInfo);
		return routeInfoId;
	}

	@Override
	public OrderStrMsg getStrInfoById(Long orderId) {
		OrderInfo orderInfo = orderService.findById(orderId);

		OrderStrMsg orderStrMsg = new OrderStrMsg();

		if (orderInfo == null
				|| orderInfo.getPayStatus() == ConstantOrderStatus.PAY_STATUS_FALSE || orderInfo.getPayStatus() == ConstantOrderStatus.PAY_STATUS_TUIKUAN) {
			orderStrMsg = null;
			// logger.info("hk getStrInfoById  order is null in DB and redis. orderId = "
			// + orderId);
			return orderStrMsg;
		}

		// 01加入订单基本属性
		orderStrMsg.setId(orderInfo.getId().toString());

		if (orderInfo.getSuccessAmount() != null) {
			orderStrMsg.setAmount(orderInfo.getSuccessAmount()
					.toEngineeringString());
		} else {
			orderStrMsg.setAmount("");
		}



		if (orderInfo.getPayStatus() != null) {
			orderStrMsg.setPayStatus(orderInfo.getPayStatus().toString());
			orderStrMsg.setPayStatusStr(PayStatusEnum.getPayStatus(orderInfo
					.getPayStatus()));
		}

		if (orderInfo.getConfirmStatus() != null) {
			orderStrMsg.setConfirmStatus(orderInfo.getConfirmStatus()
					.toString());
			orderStrMsg.setConfirmStatusStr(ConfirmStatusEnum
					.getConfirmStatus(orderInfo.getConfirmStatus()));
		}

		if (orderInfo.getOrderCreatedOn() != null) {
			orderStrMsg.setOrderCreatedOn(orderInfo.getOrderCreatedOn()
					.toString());
			orderStrMsg.setOrderCreatedOnStr(DateUtil.longToLongDate(orderInfo
					.getOrderCreatedOn()));
		}
		if (orderInfo.getOrderConfirmDate() != null) {
			orderStrMsg.setOrderConfirmDate(orderInfo.getOrderConfirmDate()
					.toString());
			orderStrMsg.setOrderConfirmDateStr(DateUtil
					.longToShortDate(orderInfo.getOrderConfirmDate()));
		}

		// 如果起息日不为空
		if (orderInfo.getOrderTradeDate() != null) {
			orderStrMsg.setOrderTradeDate(orderInfo.getOrderTradeDate()
					.toString());
			orderStrMsg.setOrderTradeDateStr(DateUtil.longToShortDate(orderInfo
					.getOrderTradeDate()));
		} else {
			// 如果起息日为空
			orderStrMsg.setOrderTradeDate(null);
			orderStrMsg.setOrderTradeDateStr("");
		}

		// 如果回款日不为空
		if (orderInfo.getDividendDate() != null) {
			orderStrMsg.setOrderDividendDate(orderInfo.getDividendDate()
					.toString());
			orderStrMsg.setOrderDividendDateStr(DateUtil
					.longToShortDate(orderInfo.getDividendDate()));
		} else {
			// 如果回款日为空
			orderStrMsg.setOrderDividendDate(null);
			orderStrMsg.setOrderDividendDateStr("");
		}

		if(orderInfo.getRealPayAmt() != null){
			orderStrMsg.setRealPayAmt(orderInfo.getRealPayAmt().setScale(2, BigDecimal.ROUND_HALF_UP).toString());	
		}
		
		if(orderInfo.getPayBackAmt() != null){
			BigDecimal payBackAmt  =  orderInfo.getPayBackAmt().setScale(2, BigDecimal.ROUND_HALF_UP);
			orderStrMsg.setPayBackAmt( payBackAmt.toString());
		}
		
		
		if (orderInfo.getDividend() != null) {
			orderStrMsg.setDividend(orderInfo.getDividend().setScale(2, BigDecimal.ROUND_HALF_UP).toString());
		}

		if (orderInfo.getExtraDividend() != null) {
			orderStrMsg.setExtraDivendend(String.valueOf(orderInfo.getExtraDividend().setScale(2, BigDecimal.ROUND_HALF_UP)).toString());
		}

		if (orderInfo.getProdDividend() != null) {
			orderStrMsg.setProdDivendend(String.valueOf(orderInfo
					.getProdDividend().setScale(2, BigDecimal.ROUND_HALF_UP)).toString());
		}

		if (orderInfo.getUserCardId() != null) {
			orderStrMsg
					.setUserCardId(String.valueOf(orderInfo.getUserCardId()));
		}

		//合同标题
		if(StringHelper.isNotEmpty(orderInfo.getContractTitle())){
			orderStrMsg.setContractTitle(orderInfo.getContractTitle());
		}

		//合同url
		if(StringHelper.isNotEmpty(orderInfo.getContractUrl())){
			orderStrMsg.setContractUrl(QN_PDF + orderInfo.getContractUrl());
			orderStrMsg.setContractUrlHTML(QN_PDF+orderInfo.getContractUrlHTML());
		}

		 
		orderStrMsg.setBenefitType(orderInfo.getBenefitType());
		
		
		// 如果支付状态为已付款，或者已还款， 则格式化相关展示
		if (orderInfo.getPayStatus() != ConstantOrderStatus.PAY_STATUS_TRUE
				&& orderInfo.getPayStatus() != ConstantOrderStatus.PAY_STATUS_PAYBACK) {
			orderStrMsg.setOrderTradeDateStr("");
			orderStrMsg.setOrderConfirmDateStr("");
			orderStrMsg.setOrderDividendDateStr("");
			orderStrMsg.setDividend("");
		}

		// 02加入顾客 及所属理财师基本属性

		SysUser user = userService.findById(orderInfo.getUserId());
		if (user != null) {
			orderStrMsg.setUserId(user.getId().toString());
			orderStrMsg.setUserName(user.getRealName());
			orderStrMsg.setUserPhoneNum(user.getName());
		}

		// 理财师信息
		if (orderInfo.getFinancialPlannerId() != null) {
			orderStrMsg.setFinancialPlannerId(orderInfo.getFinancialPlannerId()
					.toString());
			Long finUserId = orderInfo.getFinancialPlannerId();
			SysUser financialPlanner = userService.findById(finUserId);
			if (financialPlanner != null) {
				orderStrMsg.setFinancialPlannerId(financialPlanner.getId()
						.toString());
				orderStrMsg.setFinancialPlannerName(financialPlanner
						.getRealName());
				orderStrMsg.setFinancialPlannerPhoneNum(financialPlanner
						.getName());

				if (financialPlanner.getOrgId() != null) {

					Organization org = orgService.findById(financialPlanner
							.getOrgId());
					if (org != null) {
						orderStrMsg.setFinancialPlannerDepName(org.getFlag02());
					}

				}
			}
		}

		// 03 加入产品信息
		ProductInfo productInfo = productService.findById(orderInfo
				.getProductId());
		if (productInfo != null) {
			orderStrMsg.setProductId(productInfo.getId().toString());
			orderStrMsg.setProductName(productInfo.getName());
			orderStrMsg.setProductTopType(productInfo.getProdTopType()
					.toString());
			orderStrMsg.setProductTerm(productInfo.getProTermStr());
			orderStrMsg.setProductCode(productInfo.getProNo());
			Company company = comService.findById(productInfo.getIssuerId());
			if (company != null) {
				orderStrMsg.setProductCompanyId(company.getId().toString());
				orderStrMsg.setProductCompanyName(company.getName());
			}
			
			//orderStrMsg.setProRate(orderInfo.getProRate());
		}

		// 04 加入支付信息
		Long paymentId = orderInfo.getPaymentId();
		if (paymentId != null) {
			Payment payment = null;
			if (paymentService.existById(paymentId)) {
				payment = paymentService.findById(paymentId);
			} else if (11111111L == paymentId) {// 富友金账户
				Long userId = orderInfo.getUserId();
				HqlFilter filter = new HqlFilter();
				filter.addEQFilter("userId", userId);
				filter.addEQFilter("cardStatus",
						CardStatusCode.PAYMENT_DISPLAY_SHOW);
				filter.addSql(" and supportCompany like '1%' ");
				List<Payment> paymentList = paymentService.findByFilter(filter);
				if (paymentList.size() > 0) {
					payment = paymentList.get(0);

				}

			}
			if (payment != null) {
				orderStrMsg.setPaymentId("" + paymentId);
				orderStrMsg.setPaymentBankCardNo(payment.getPaymentNo());
				orderStrMsg.setPaymentBankName(payment.getBankName());
				orderStrMsg.setIdentity(payment.getIdentityNo());
				orderStrMsg.setPaymentUserName(payment.getAccountName());
			}
		}

		// 05. 给定单添加组织架构，并且增加组织架构描述
		if (orderInfo.getOrgId() != null) {
			orderStrMsg.setOrgId(String.valueOf(orderInfo.getOrgId()));
			Organization org = orgService.findById(orderInfo.getOrgId());
			if (org != null) {
				orderStrMsg.setOrgName(org.getFlag02());
			}
		}

		// 06. 设置渠道描述
		if (orderInfo.getChannel() != null) {
			Integer channelId = orderInfo.getChannel();
			String channelName = userChannelService.getChannelNameByChannelId(channelId);
			orderStrMsg.setChannelName(channelName);
			orderStrMsg.setChannel(channelId.toString());
		}
		
		
		return orderStrMsg;
	}

	@Override
	public OrderInfo findById(long id) {

		return getById(id);
	}

	@Override
	public OrderCreateMsg createOrder(Long productId, Long userId,
			Long PaymentId, Long userCardId) {
		// TODO Auto-generated method stub
		logger.info(
				"HkOrderHandleImpl createOrder create orderInfo productId = {},"
						+ " userId = {}, paymenntId = {}, userCardId = {}"
						+ productId, userId, PaymentId, userCardId);

		OrderInfo orderInfo = createOrderInfo(productId, userId, PaymentId);
		Long orderId = orderInfo.getId();

		logger.info("HkOrderHandleImpl orderId = {}", orderId);
		if (userCardId != 0L) {
			RedisCilent.setString(CacheConstants.FY_USERCARD_ORDERINFO
					+ orderId, String.valueOf(userCardId), 172800);
			// UserCard userCard = userCardService.findById(userCardId);
			// userCardService.updateUserCardInfo(userCard,
			// ConstantCart.CARD_STATUS_ACTIVE, orderId);
		}
		RedisCilent.setString(CacheConstants.FY_CREATE_ORDERINFO + orderId,
				new JSONObject(orderInfo).toString(), 172800);
		OrderCreateMsg respMsg = new OrderCreateMsg();
		respMsg.setOrderId(orderId);

		return respMsg;
	}

	private OrderInfo createOrderInfo(Long productId, Long userId,
			Long PaymentId) {
		logger.info("hk createOrderInfo create orderInfo productId = "
				+ productId + "  userId = " + userId);
		SysUser user = userService.findById(userId);
		// 创建订单，用于保存在数据库
		OrderInfo orderInfo = new OrderInfo();
		orderInfo.setProductId(productId);
		orderInfo.setUserId(userId);

		Long orderId = LongIdThreadSafety.get();
		orderInfo.setId(orderId);
		orderInfo.setCompanyId(ConstantRoute.COMPANY_HUAKANG);
		orderInfo.setBrokerOrderNo("hk" + orderId.toString());
		orderInfo.setPayStatus(ConstantOrderStatus.PAY_STATUS_FALSE);
		orderInfo
				.setConfirmStatus(ConstantOrderStatus.CONFIRM_STATUS__NO_CONFIRM);
		orderInfo.setOrderCreatedOn(System.currentTimeMillis());

		// 添加渠道信息，默认渠道信息为无主客户服务部
		if (user.getChannel() != null) {
			orderInfo.setChannel(user.getChannel());
		} else {
			orderInfo.setChannel(ConstantUserChannel.USER_CHANNEL_WUZHU);
		}

		if (userService.getFinUserIdByUserId(userId) != null) {
			Long finUserId = userService.getFinUserIdByUserId(userId);
			orderInfo.setFinancialPlannerId(finUserId);
			SysUser financialUser = userService.findById(finUserId);
			if (financialUser != null) {
				if (financialUser.getOrgId() != null) {
					int orgId = financialUser.getOrgId();
					// 给订单添加组织架构id
					orderInfo.setOrgId(orgId);
				}
			}
		}

		// 保存支付方式
		orderInfo.setPaymentId(PaymentId);

		return orderInfo;
	}

	@Override
	public OrderInfo createFYJZHOrder(Long productId, Long userId,
			Long userCardId, BigDecimal amount) {
		logger.info("productId ={}, userId={}, userCardId={}, amount={}",
				productId, userId, userCardId, amount);
		OrderInfo order = orderService.initOrder(null, userId, productId,
				userCardId, amount);

		if(order == null){
			logger.error("订单初始化失败");
			return order;
		}
		System.out.println("order mes = " + order);

		// 保存在redis 中
		if( order.getPayStatus() != null && order.getPayStatus() != ConstantOrderStatus.PAY_STATUS_TRUE){
			RedisCilent.setString(ConstantsOrder.ORDER_FYJZH_PRIX + order.getId(),
					new JSONObject(order).toString(), 172800);
		}else{
			orderService.add(order);
			orderRouteService.addByOrder(order);
		}
		logger.info("order will add into db orderId = " + order.getId());
		return order;
	}

}
